package com.example.onlineeducation.repository

import com.example.onlineeducation.data.entity.ProblemEntity
import com.example.onlineeducation.data.json.OnlineExaminationFinishJson
import com.example.onlineeducation.mapper.OnlineExaminationQuestionsMapper
import com.example.onlineeducation.net.ApiService
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.yc.jetpacklib.base.YcRepository
import com.yc.jetpacklib.extension.ycFlow
import com.yc.jetpacklib.extension.ycToRequestBody
import com.yc.jetpacklib.net.YcResult
import kotlinx.coroutines.flow.*
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

/**
 * Creator: yc
 * Date: 2022/4/20 16:08
 * UseDes:线下相关仓库
 */
class OnlineRepository(private val apiService: ApiService) : YcRepository() {
    private val mOnlineExaminationQuestionsMapper by lazy { OnlineExaminationQuestionsMapper() }

    /**
     * 获取线下学习列表
     */
    fun getExaminationProblemList(examinationId: String): Flow<YcResult<List<ProblemEntity>?>> = ycFlow {
        val json = apiService.getExaminationProblemList(examinationId)
        send(YcResult.Success(mOnlineExaminationQuestionsMapper.map(json.dataList)))
    }

    /**
     * 完成线上考试
     * @param proId String                      项目id
     * @param examinationId String              考试id
     * @param problemList List<ProblemEntity>   考题结果
     */
    fun getExaminationFinish(proId: String, examinationId: String, problemList: List<ProblemEntity>): Flow<YcResult<OnlineExaminationFinishJson>> = ycFlow {
        val requestData = JsonObject()
        try {
            requestData.addProperty("examId", examinationId)
            requestData.addProperty("projId", proId)
            val questionList = JsonArray()
            problemList.map {
                questionList.add(JsonObject().apply {
                    addProperty("questionId", it.questionId)
                    add("optionIds", JsonArray().apply {
                        it.optionList?.map {
                            if (it.isSelect) {
                                add(it.optionId)
                            }
                        }
                    })
                })
            }
            requestData.add("questionList", questionList)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        val requestBody = requestData.toString().ycToRequestBody()
        val json = apiService.getExaminationFinish(requestBody)
        send(YcResult.Success(json.data!!))
    }
}